-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.
--
-- Create: 2025-7-21
-- Description: remote single board object.
local class = require 'mc.class'
local comm = require 'common'
local log = require 'mc.logging'
local const = require 'constants'

local object = class{}

function object:ctor(mdb_obj, failover_sig, name)
    self.name = name
    self.mdb_obj = mdb_obj
    self.rule_type = mdb_obj.RuleType
    self.direction = mdb_obj.Direction
    self.description = mdb_obj.Description
    self.operator = mdb_obj.Operator
    self.state = false
    self.failover_sig = failover_sig
end

function object:initialize()
    -- 开启监听
    self.mdb_obj.property_changed:on(function(name, value, _)
        if name ~= 'Reading' or not self.mdb_obj.Enabled then
            return
        end
        self:check_condition(value)
    end)
    -- 初始值检测
    if self.mdb_obj.Enabled then
        self:check_condition(self.mdb_obj.Reading)
    end
end

function object:check_condition(reading)
    local current_state = comm.compare(self.operator, reading, self.mdb_obj.Threshold)
    if current_state == self.state then
        return
    end
    -- 状态变化
    self.state = current_state
    log:notice('switch rule [%s] status change to [%s] while reading [%s]', self.name, current_state, reading)
    -- 主动切换条件命中时需要发送倒换请求
    if current_state and self.rule_type == const.SWITCH_RULE_TYPE_ALLOW then
        self.failover_sig:emit(self.direction)
    end
end

return object